﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using static FmAPI.Comm;

namespace WeatherComm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public async void button1_Click(object sender, EventArgs e)
        {
            var a = await HttpHelper.GetHtmlAsync("https://www.sojson.com/time/jieqi-lichun.html");

            var d = new OpenFileDialog();
            var ret = d.ShowDialog();
            if (ret != DialogResult.OK)
            {
                return;
            }

            var ls = CityInfo2.GetFromFile(d.FileName);
            CityInfo2.Write2Db(ls);

        }

        private List<CityInfo2> CityInfoList;
        private void Form1_Load(object sender, EventArgs e)
        {
            CityInfoList = CityInfo2.GetFromDb();
            dataGridView1.DataSource = new BindingList<CityInfo2>(CityInfoList);
            foreach (DataGridViewColumn c in dataGridView1.Columns)
            {
                c.Visible = c.Name.Contains("city") || c.Name.Contains("Enable");
            }

            dataGridView1.RowHeadersVisible = false;
        }

        private void DataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex < 0)
            {
                return;
            }
            if (e.RowIndex < 0)
            {
                return;
            }

            if (dataGridView1.Columns[e.ColumnIndex].Name == "Enable")
            {
                return;
            }
            var curr = dataGridView1.Rows[e.RowIndex];
            var code = curr.Cells["city_code"].Value.ToString().Trim();
            var ServiceUri = ConfigurationManager.AppSettings["ServiceUri"];
            if (string.IsNullOrEmpty(code))
            {
                return;
            }
            var value = RootData.GetDataFromNet($"{ServiceUri}{code}");
            //textBox1.Text = JsonConvert.SerializeObject(value);
            var ret = value != null && RootData.Write2Db(value);
            textBox1.Text += ret ? "成功 \r\n" : "失败 \r\n";
        }

        private void Timer1_Tick(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            foreach (var r in CityInfoList)
            {
                try
                {
                    if (!r.Enable)
                    {
                        continue;
                    }
                    var ServiceUri = ConfigurationManager.AppSettings["ServiceUri"];
                    var value = RootData.GetDataFromNet($"{ServiceUri}{r.city_code}");
                    var ret = value != null && RootData.Write2Db(value);
                    if (ret)
                    {
                        Write2Fm(value, r.id);

                    }

                    //Thread.Sleep(2000);
                }
                catch
                {
                    continue;
                }
            }

            timer1.Enabled = true;
        }

        private bool Write2Fm(RootData value, int cityId)
        {
            try
            {
                SetValues($"VA.HIGH{cityId}|VA.LOW{cityId}",
                    $"{Convert.ToSingle(value.data.forecast[0].high)}|{Convert.ToSingle(value.data.forecast[0].low)}");
                return true;
            }
            catch
            {
                return false;
            }
        }

        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
          
        }

        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
           
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
           
        }

        private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            //if (e.RowIndex < 0)
            //{
            //    return;
            //}
            //if (e.ColumnIndex < 0)
            //{
            //    return;
            //}

           

           
        }

        private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
           
        }

        private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (dataGridView1.CurrentCell == null)
            {
                return;
            }
            var columnIndex = dataGridView1.CurrentCell.ColumnIndex;
            if (dataGridView1.Columns[columnIndex].Name != "Enable")
            {
                return;
            }
            var row = dataGridView1.CurrentRow;
            if (!(dataGridView1.DataSource is BindingList<CityInfo2> ls))
            {
                return;
            }

            if (row == null) return;

            var id = (int)row.Cells["id"].Value;
            var ef = new EfHelper<WeatherDataDb>();
            var r = ef.GetNow<City>(p => p.ID == id);
            if (r.Enable == (bool)row.Cells["Enable"].EditedFormattedValue) return;

            r.Enable = (bool)row.Cells["Enable"].EditedFormattedValue;
            var ret = ef.Update(r);

            if (ret)
            {
                textBox1.Text += $@"{r.CityName}修改成功为 {r.Enable} " + "\r\n";
            }
        }

        private readonly EfHelper<EF_DBFirst.WeatherEntities> _efHelper = new EfHelper<EF_DBFirst.WeatherEntities>();
        private void button2_Click(object sender, EventArgs e)
        {
            var ls = _efHelper.GetList<EF_DBFirst.City>().ToList();
            
            dataGridView1.DataSource = new BindingList<EF_DBFirst.City>(ls);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            dataGridView1.DataSource = null;
        }
    }
}
